package oc.tm.sg.admin.memory.factory.impl;

import javax.sql.DataSource;

import oc.tm.sg.admin.memory.MemoryConf;
import oc.tm.sg.admin.memory.factory.MemoryFactory;

import com.alibaba.druid.pool.DruidDataSource;

public class MysqlMemory implements MemoryFactory {

	private static DruidDataSource dataSource = null;
	public static final String driver="com.mysql.jdbc.Driver";
	
	public void init(MemoryConf conf) throws Exception {
		try {
            dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driver);
            dataSource.setUrl(conf.getJdbcUrl());
            dataSource.setUsername(conf.getUserName());
            dataSource.setPassword(conf.getPassword());
            
            
            dataSource.setInitialSize(5);
            dataSource.setMinIdle(1);
            dataSource.setMaxActive(10);

            //初始化连接数量
            dataSource.setInitialSize(conf.getInitialSize());
        	//配置获取连接等待超时的时间
            dataSource.setMaxWait(conf.getMaxWait());;
        	//最小空闲连接数
            dataSource.setMinIdle(conf.getMinIdle());
        	//配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
            dataSource.setTimeBetweenEvictionRunsMillis(conf.getTimeBetweenEvictionRunsMillis());
        	//配置一个连接在池中最小生存的时间，单位是毫秒
            dataSource.setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis());
        	//开启Druid的监控统计功能  
            dataSource.setFilters(conf.getFilters());
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

	public DataSource getDataSource() {
		return dataSource;
	}

	public void destroy() throws Exception {
		if(dataSource!=null){
			dataSource.close();
		}
	}

}
